package com.zcx.webview;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private WebView wv;
    private Button bt_full;//全屏播放按钮
    private TextView loading;//加载控件
    private Boolean isExit=false;//是否退出
    private String url="http://www.vultr1.com/";//网站url
    private String playUrl="";//播放的url地址

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        wv=findViewById(R.id.wv);
        bt_full=findViewById(R.id.bt_full);
        bt_full.setVisibility(View.GONE);
        loading=findViewById(R.id.loading);

        WebSettings settings = wv.getSettings();
        //设置的WebView用户代理字符串
        settings.setUserAgentString("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
        //启用JavaScript
        settings.setJavaScriptEnabled(true);
        //启用插件
        settings.setPluginState(WebSettings.PluginState.ON);
        //让JavaScript自动打开窗口
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        //设置DOM存储API是否已启用
        settings.setDomStorageEnabled(true);
        //设置是否从网络web视图不应加载图像资源（通过http和https URI方案访问的资源）
        settings.setBlockNetworkImage(false);
        //套的WebView是否应使用其内置的缩放机制
        settings.setBuiltInZoomControls(true);
        //设置的WebView是否应该保存的表单数据
        settings.setSaveFormData(true);
        //这种方法在API层面18.保存密码中的WebView不会在将来的版本中支持已被否决
        settings.setSavePassword(true);
        //设置使用内置变焦机制，当web视图是否应显示在屏幕缩放控制
        settings.setDisplayZoomControls(true);
        //设置是否WebView中是否支持多个窗口
        settings.setSupportMultipleWindows(true);
        //设置的WebView是否需要用户手势媒体播放
        settings.setMediaPlaybackRequiresUserGesture(true);

        wv.loadUrl(url);
        //String str="<html><body><script>function showAndroidToast(toast){android.alter(toast);}</script><input type='button' value='Say hello' onClick='showAndroidToast(\"Hello Android!\")'/></body></html>";
        //wv.loadData(str,"text/html" ,"utf-8");
        //wv.addJavascriptInterface(new WebAppInterface(this),"android");
        wv.setWebViewClient(new MyWebViewClient());

    }

    //监听全屏点击事件
    public void onFullScreen(View view) {
        Intent intent = new Intent(this,PlayActivity.class);
        intent.putExtra("url",playUrl);
        Toast.makeText(this,playUrl,Toast.LENGTH_LONG).show();
        startActivityForResult(intent,0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(requestCode==0){//视频播放
            switch (resultCode){
                case RESULT_CANCELED:
                    break;
                case 3://播放完成
                    Toast.makeText(this,"视频已播完",Toast.LENGTH_LONG).show();
                    break;
                case 4://发生错误
                    Toast.makeText(this,
                            String.format("what:%d,extra:%d",data.getIntExtra("what",0),
                                    data.getIntExtra("extra",0)),
                            Toast.LENGTH_LONG).show();
                    break;
                default:
                    Toast.makeText(this,"视频播放出错",Toast.LENGTH_LONG).show();
            }
        }
    }

    //android与javascript交互接口
    public class WebAppInterface{
        private Context c;
        WebAppInterface(Context c){
            this.c=c;
        }

        @JavascriptInterface
        public void alter(String toast){
            Toast.makeText(MainActivity.this,toast,Toast.LENGTH_LONG).show();
            wv.loadUrl(url);
        }

    }

    public class MyWebViewClient extends WebViewClient{
        private String TAG="MyWebViewClient";
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            loading.setVisibility(View.VISIBLE);
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            //Log.e(TAG,url);
            /**
            if(url.contains("http://www.bihaijx.com/kkm3u8.php")){//加载酷云视频
                playUrl=url.substring(url.indexOf("url=")+4);
            }
            if(url.contains("https://www.ixxplayer.com/video.php")){//加载狗带云视频
                playUrl=url.substring(url.indexOf("url=")+4);
            }
            if(url.contains("https://api.123zx.net/m3u8.php")){//加载最快云/33uu云视频
                playUrl=url.substring(url.indexOf("url=")+4);
            }
            if(url.contains("http://api.zuilingxian.com/jiexi.php")){//加载腾讯视频
                playUrl=url.substring(url.indexOf("url=")+4);
            }
            **/
            if(url.contains("?url=")){//加载视频
                playUrl=url.substring(url.indexOf("url=")+4);
            }
            super.onLoadResource(view,url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            loading.setVisibility(View.GONE);
            if(url.contains("http://www.vultr1.com/play")
                    ||url.contains("http://www.vultr1.com/index.php/play")){
                bt_full.setVisibility(View.VISIBLE);
            }else {
                bt_full.setVisibility(View.GONE);
            }
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            Log.e(TAG,error.toString());
        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            Log.e(TAG,errorResponse.toString());
        }
    }

    @Override
    public void onBackPressed() {
        if(wv.canGoBack()) {
            wv.goBack();
        }else {
            if(isExit) {
                super.onBackPressed();
            }else {
                Toast.makeText(this,"再按一次退出",Toast.LENGTH_LONG).show();
                isExit=true;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        wv.clearCache(true);
        wv=null;
    }
}
